package com.itheima.log;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.pojo.SysLog;
import com.itheima.service.LogService;
import com.itheima.util.IpAddressUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @ClassName LogService
 * @Description
 * @Author yuanying
 * @Date 2020/3/8 0:19
 * @Version 1.0
 */
@Component
@Aspect
public class LogWebService {

    @Reference
    LogService logService;

    @Pointcut("execution(* com.itheima.controller.*.*(..))")
    public void pointcutLog(){}

    @Around(value = "pointcutLog()")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        RequestMapping annotation = methodSignature.getMethod().getAnnotation(RequestMapping.class);

        SysLog sysLog = new SysLog();
        sysLog.setCreateDate(new Date());
        sysLog.setIp(IpAddressUtil.getIpAdrress(request));
        sysLog.setMethod(JSON.toJSONString(annotation.value()));
        if(user != null){
            sysLog.setUsername(user.getUsername());
        }

        Object obj;
        try {
            // 请求接收的参数args
            Object[] args = pjp.getArgs();
            sysLog.setParams(JSON.toJSONString(args));
            //执行目标方法
            obj = pjp.proceed();
            String s = JSON.toJSONString(obj);
            if (s.length() > 255) {
                System.out.println("结果为:"+s);
                s=s.substring(0,254);
            }
            sysLog.setResult(s);

        } catch (Throwable t) {
            throw t;
        } finally {
            logService.saveLog(sysLog);
        }
        return obj;
    }
}
